/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package assignment1;

import java.io.IOException;
import java.util.Vector;

/**
 *
 * @author cjaramillo
 */
public class InferenceEngine {
    Knowledgebase m_knowledgebase;
    Database m_database;
    boolean m_unsolvable;
    
    InferenceEngine()
    {
        m_unsolvable = false;
    }
    
    public void knowledgebase(Knowledgebase knowledgebase)
    {
        m_knowledgebase = knowledgebase;
    }
    
    public void database(Database database)
    {
        m_database = database;
    }
    
    public boolean solved()
    {
        boolean retVal = false;
        if(m_database.rover().x() == m_database.fullBoard().targetColumn() &&
                m_database.rover().y() == m_database.fullBoard().targetRow())
        {
            System.out.println("Target reached");
            retVal = true;
        }
        else if(m_unsolvable)
        {
            System.out.println("Unsolvable with current rules");
            retVal = true;
        }
        return retVal;
    }
    
    public String cycle() throws IOException
    {
        String log = "";
        Vector<Rule> rules = m_knowledgebase.rules();
        if(rules.size() == 0)
        {
            //Continue to allow user input rules until I code auto rules
            Rule ruleToFire = m_knowledgebase.getRuleToFire(m_database);   
            log += "\nFired rule:\n\t" + ruleToFire;
            log += ruleToFire.fire(m_database.rover());
        }
        else
        {
            boolean ruleFired = false;
            int currentRule = 0;
            while(!ruleFired && currentRule < rules.size())
            {
                Rule rule = rules.elementAt(currentRule);
                if(rule.evaluate(m_database))
                {
                    log += "\n\nFired rule:\n\t" + rule;
                    log += rule.fire(m_database.rover());
                    ruleFired = true;
                }
                currentRule++;
            }
            if(!ruleFired)
            {
                System.out.println("No rules to fire Final State:");
                m_unsolvable = true;
            }
        }
        return log;
    }
}
